package us.gaaoc.framework.webapp.backingbeans.agent;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.UIParameter;
import javax.faces.component.UISelectOne;
import javax.faces.context.FacesContext;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import javax.faces.validator.ValidatorException;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.hibernate.Hibernate;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.transaction.annotation.Transactional;

import us.gaaoc.cms.sustain.vo.Organization;
import us.gaaoc.framework.model.Attorney;
import us.gaaoc.framework.model.CaseRecord;
import us.gaaoc.framework.model.CaseRecordEventType;
import us.gaaoc.framework.model.CaseRecordIdExternalCaseRecordNumber;
import us.gaaoc.framework.model.CaseRecordHistory;
import us.gaaoc.framework.model.CaseRecordStatus;
import us.gaaoc.framework.model.Court;
import us.gaaoc.framework.model.CourtEvents;
import us.gaaoc.framework.model.DocumentPackage;
import us.gaaoc.framework.model.DocumentStatus;
import us.gaaoc.framework.model.Documents;
import us.gaaoc.framework.model.LdapDirectoryPerson;
import us.gaaoc.framework.model.LegalPreparer;
import us.gaaoc.framework.model.OrgParticipants;
import us.gaaoc.framework.model.OrganizationAddress;
import us.gaaoc.framework.model.Organizations;
import us.gaaoc.framework.model.Person;
import us.gaaoc.framework.model.PersonOrganizations;
import us.gaaoc.framework.model.PersonParticipants;
import us.gaaoc.framework.model.Signatures;
import us.gaaoc.framework.model.constants.Constants;
import us.gaaoc.framework.signature.digital.DigitalSignerController;
import us.gaaoc.framework.signature.visual.PDFStamper;
import us.gaaoc.framework.signature.visual.PDFStamperController;
import us.gaaoc.framework.util.DateUtil;
import us.gaaoc.framework.util.LocalCaseInformation;
import us.gaaoc.framework.util.io.FileUtility;
import us.gaaoc.framework.webapp.backingbeans.BaseBackingBean;
import us.gaaoc.framework.webapp.backingbeans.attorney.actions.SendToCourtAction;
import us.gaaoc.framework.webapp.backingbeans.clerk.actions.GenericImportAction;
import us.gaaoc.framework.webapp.util.Messages;
import us.gaaoc.framework.signature.visual.PDFStamperController;
import us.gaaoc.framework.signature.digital.DigitalSignerController;
import us.gaaoc.framework.model.Counter;
import us.gaaoc.framework.model.CounterPerSigner;
/**
 * 
 * @author hea
 * @date Apr 19, 2006
 * @version: GAJE 1.5
 * 
 */
@SuppressWarnings("unchecked")
public class CaseDetailsPage extends BaseBackingBean {

	/**
	 * 
	 */
	private static final long serialVersionUID = 4728656749052254744L;

	/**
	 * properties
	 */
	private CaseRecord caseRecord;
	
	private String caseRecordUuid;
	
	private String filerName;
	
	private String OCSSCaseNumber;
	
	private String courtCaseNumber;
	
	private boolean renderSignedText;
	
	
	
	
	
	
	/**
	 * Data Models for the personParticipants
	 */
	private DataModel initiatingPartyPersonModel;

	private DataModel defendentPartyPersonModel;

	private DataModel witnessPersonModel;

	private DataModel plantiffsAttorneyModel;

	private DataModel defendentsAttorneyModel;

	private DataModel initiatingPartyOrganizationDataModel;

	private boolean renderSetCourtDate;
	


	
	private boolean renderModifyButton;
	private boolean renderSendToAttorneyButton;
	
	private boolean renderSignButton;
	
	private boolean renderSendToClerkButton;
	
	private boolean renderRejectReason;
	
	private String signatureTrackingID;
	
	private FacesMessage message;

	
	private boolean renderUpdateCourtCaseNumber;
	
	private String jurisdiction;
	
	private boolean renderFileNewDocuments;

	
	private DigitalSignerController digitalSignerController = new DigitalSignerController();

	private PDFStamperController pdfStamperController= new PDFStamperController();

	private String courtUuid;

	
	/**
	 * List of Imported Documents
	 */
	private List<Documents> importedDocumentsList;
	private DataModel importedDocumentsModel;
	
	/**
	 * List of Uploaded Documents
	 */
	private List<Documents> uploadedDocumentsList;
	private DataModel uploadedDocumentsModel;
	
	private Date courtDate, proposedCourtDate ;

	private Logger LOG = Logger.getLogger(CaseDetailsPage.class);

	
	private String caseCaption;

	private List<Documents> documentList = new ArrayList<Documents>();

	private String organizationName = null;
	
	private UIParameter signatureBinding;
	

	private UIParameter documentClicked_Uploaded;
	
	private UIParameter documentClicked_Imported;
	
	
	private DataModel signaturesListModel;

	private List<Signatures> signaturesList;

	private DataModel sigantureCounterPerSignerModel;

	private CounterPerSigner signatureCounterPerSigner;

	private DataModel signatureCounterModel;

	private Counter signatureCounter;

	 private Documents signedDoc;

	private Documents docSignedByThisPerson;

	private String signatureConfTrackNumber;

	
	private boolean judgeVisible;
	
	public void setJudgeVisible(boolean judgeVisible) {
		this.judgeVisible = judgeVisible;
	}
	
	public boolean isJudgeVisible() {
		return judgeVisible;
	}

	
	/**
	 * Choosing attorney patch
	 */
	private boolean isRenderChooseAttorney = true;
	private String chooseAttorneyValue;
	private UISelectOne chooseAttorneyBinding;
	
	private ArrayList<SelectItem> chooseAttorneyValueItems;

	private boolean validCase;
	
	
	private boolean renderCourtDate;
	
	private String comments;
    
    
    public String getComments() {
            return comments;
    }

    public void setComments(String comments) {
            this.comments = comments;
    }
    
	SendToCourtAction sendToCourtAction = new SendToCourtAction();

	

	public ArrayList<SelectItem> getChooseAttorneyValueItems() {
		chooseAttorneyValueItems = new ArrayList<SelectItem>();
		
		Person p = (Person) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("person");
		Court c = (Court) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("court");
		Organizations o = ((PersonOrganizations)this.getModelFacade().findPersonOrganizationByCourtAndPerson(p,c.getUuid())).getOrganization();
		chooseAttorneyValueItems = new ArrayList<SelectItem>();
		List<LegalPreparer> packageTypeList = this.getModelFacade().getLegalPreparers(p, o);
		for (LegalPreparer lp : packageTypeList) {
			
			Person aPerson = lp.getAttorney().getPerson();
			//String attorneyName = aPerson.getFirstName() + aPerson.getLastName() + " " + this.getModelFacade().getBarID(aPerson, c);
			String attorneyName = aPerson.getFirstName() + " " + aPerson.getLastName();
			
			//chooseAttorneyValueItems.add(new SelectItem(lp.getAttorney().getUuid(),attorneyName));
			chooseAttorneyValueItems.add(new SelectItem(lp.getAttorney().getPerson().getUuid(),attorneyName));
		}
		return this.chooseAttorneyValueItems;
	}
	
	public void getChooseAttorneyValueItems(ArrayList<SelectItem> i) {
		this.chooseAttorneyValueItems = i;
	}
	
	
	/**
	 * Constructor
	 *
	 */
	public CaseDetailsPage() {
		Map sessionMap = this.getFacesContext().getExternalContext().getSessionMap();
		courtUuid = (String) sessionMap.get("courtUuid");
		Person p = (Person) sessionMap.get("person");
		String caseUuid = (String) sessionMap.get("caseUuid");

		this.setRenderCourtDate(p.isSetCourtDate());
		if(caseUuid!=null)
		this.loadData();
	}

	public void setProposedJudge(String proposedJudge) {
		this.proposedJudge = proposedJudge;
	}
	public String getProposedJudge() {
		return proposedJudge;
	}
	private String proposedJudge;
	public String updateJudge()
	{
		// Add an entry into the case record history for the setting of the judge
		Map sessionMap = this.getFacesContext().getExternalContext().getSessionMap();	
		
		
		if(proposedJudge == null || proposedJudge.trim().equalsIgnoreCase(""))
		{
			proposedJudge = "no judge";
		}
		
		this.getModelFacade().addCaseRecordHistory(
				(String) sessionMap.get("caseUuid"),
				52, 
				 (Person) sessionMap.get("person"),
				courtUuid,
				proposedJudge);
		
		return "stay";
	}
	
	/**
	 * This method loads the data from the database for the particular 
	 * filing.
	 * 
	 *  Session map input:
	 *  	caseUuid - the case record UuId
	 *  	courtUuid - the court Uuid 
	 *  	from - the page we navigated from (?????)
	 * 
	 */
	private void loadData() {
		validCase = true;
		
		Map sessionMap = this.getFacesContext().getExternalContext().getSessionMap();
		String caseUuid = (String) sessionMap.get("caseUuid");
		//System.out.println("The Case UUid" +caseUuid);
		
		//System.out.println();
		CaseRecord c = this.getModelFacade().findCaseRecordById(caseUuid, courtUuid);
		Court court = this.getModelFacade().findCourt(courtUuid);
		//System.out.println("The court ID :" +courtUuid);

		Person p = (Person) sessionMap.get("person");
		//System.out.println("the person who logged in is :" +p.getFirstName());
		Organizations org = ((PersonOrganizations)this.getModelFacade().findPersonOrganizationByCourtAndPerson(p,c.getCourt().getUuid())).getOrganization();
		//System.out.println("The Org name is " + org.getName());
		this.setCaseRecord(c);
		//Render UpdateCourtCaseNumber button
		this.setRenderUpdateCourtCaseNumber(p.isSetCivilActionNumber());

		
		
		if(court.getUuid().equals("courtUuidHart") || court.getUuid().equals("courtUuidCoweta") || court.getUuid().equals("courtUuidMeriwether"))
		{
			this.setJudgeVisible(true);
		}
		
		
		
		//Render reject reason
		int caseRecordStatus = c.getStatus().getCode();
		if (caseRecordStatus == 8) {
			this.setRenderRejectReason(true);
		}
		
		
		// re-add to fix issue:
		//  b7006e6c-695c-11dd-945f-00301b45ff56
		Hibernate.initialize(c.getPersonParticipants());
		Hibernate.initialize(c.getOrgParticipants());
		Hibernate.initialize(c.getDocuments());
		Hibernate.initialize(c.getStatus());
		Hibernate.initialize(c.getLocalCaseCategory());
		Hibernate.initialize(c.getLocalCaseDivision());
		Hibernate.initialize(c.getLocalCaseFilingType());
		Hibernate.initialize(c.getLocalCaseType());
		
		for (int i=0; i< c.getPersonParticipants().size(); i++) {		
			Hibernate.initialize(c.getPersonParticipants().get(i).getPerson().getAddresses());
			for (int j=0; j< c.getPersonParticipants().get(i).getPerson().getAddresses().size(); j++) {
					
				Hibernate.initialize(c.getPersonParticipants().get(i).getPerson().getAddresses().get(j).getAddress());
			}
		}
		for (int i=0; i< c.getOrgParticipants().size(); i++) {
			Hibernate.initialize(c.getOrgParticipants().get(i).getOrganizations().getAddresses());
			for (int j=0; j< c.getOrgParticipants().get(i).getOrganizations().getAddresses().size(); j++) {
				Hibernate.initialize(c.getOrgParticipants().get(i).getOrganizations().getAddresses().get(j).getAddress());
			}
		}
		
		for (int i = 0; i < c.getDocuments().size(); i++) {
			Hibernate.initialize(c.getDocuments().get(i).getDocumentInstance());
		}	
		//------------------------------
		
		try {
			this.setJurisdiction(LocalCaseInformation.getJurisdiction(courtUuid));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		List<PersonParticipants> pParticipantsList = c.getPersonParticipants();
		List<OrgParticipants> oParticipantsList = c.getOrgParticipants();	
		 
		List <OrgParticipants>initiatingPartyOrganizationList = new ArrayList<OrgParticipants>();

		// for initiating party person list
		List initiatingPartyPersonList = new ArrayList();

		// for defendent party person list
		List defendentPartyPersonList = new ArrayList();

		// for witness person list
		List witnessPersonList = new ArrayList();

		// for plantiff's Attorneys
		List plantiffsAttorneyList = new ArrayList();

		// for defendent's Attorneys
		List defendentsAttorneyList = new ArrayList();

		for (OrgParticipants o : oParticipantsList) {
			if (o.getRelationship().getCode()== 1 )
				initiatingPartyOrganizationList.add(o);
			
		}
		/* to test */
		for (OrgParticipants o : initiatingPartyOrganizationList) {
			List <OrganizationAddress> addresses = o.getOrganizations().getAddresses();
			for(OrganizationAddress oa : addresses) {
				if(oa.getAddressType().getUuid().equals("addressTypeUuid1"))//for primary contact address
					System.out.println(oa.getAddress().getCityName());
				break;
			}
			
		}

		PersonParticipants kcr = null; 
		
		this.setFilerName("");
		
		for (PersonParticipants o : pParticipantsList) {
			if (o.getRelationship().getCode() == 1)
				initiatingPartyPersonList.add(o);
			else if (o.getRelationship().getCode() == 2)
				defendentPartyPersonList.add(o);
			else if (o.getRelationship().getCode() == 3)
				witnessPersonList.add(o);
			else if (o.getRelationship().getCode() == 4 && !o.getPerson().getFirstName().equalsIgnoreCase("ff20da2c-8e5c-11dd-9b78-0016d3"))
			{
				if(c.getCaseTrackingId() != null && 
						!c.getCaseTrackingId().trim().equalsIgnoreCase(""))
				{
					this.setRenderChooseAttorney(false);
				}else{
					if(this.getModelFacade().getLegalPreparers(p, org).size() > 1)
					{
						this.setRenderChooseAttorney(true);
					}
				}
				
				String barID = this.getModelFacade().getBarID(o.getPerson(), court);
				if (barID.equals("597910")) { 
					kcr = o;
				}
				
				Attorney a = new Attorney();
				a.setBarID(this.getModelFacade().getBarID(o.getPerson(), court));
				a.setPerson(o.getPerson());
				o.getPerson().setAttorney(a);
				plantiffsAttorneyList.add(o);
			}
			else if (o.getRelationship().getCode() == 5)
				defendentsAttorneyList.add(o);
			else if (o.getRelationship().getCode() == 6) {
				Person filer = o.getPerson();
				this.setFilerName(
						this.getFilerName() + " , " + 						
						filer.getFirstName() + " "
						+ filer.getMiddleName() + " " + filer.getLastName());
			}
		}
		
		this.setFilerName(this.getFilerName().replaceFirst(",",""));
		
		//The following block is for Fulton's SAAG office Kathryn C. Reeder
		if(courtUuid.equalsIgnoreCase("courtUuid4"))
		{
			Person person = this.getModelFacade().findAttorneyByBarIDAndOrgAsPerson("597910", "initiatingPartyOrganizationUuid4");
			if(person != null)
			{
				List<PersonParticipants> ppList = this.getModelFacade().getPersonParticipantByPerson(person);
				if (!ppList.isEmpty() && this.getModelFacade().getPersonParicipant(c).contains(person)){
					plantiffsAttorneyList.clear();
					plantiffsAttorneyList.add(kcr);
				}
			}
		}
		//End
		
		initiatingPartyOrganizationDataModel = new ListDataModel();
		initiatingPartyOrganizationDataModel
				.setWrappedData(initiatingPartyOrganizationList);
		
		initiatingPartyPersonModel = new ListDataModel();
		initiatingPartyPersonModel.setWrappedData(initiatingPartyPersonList);

		defendentPartyPersonModel = new ListDataModel();
		defendentPartyPersonModel.setWrappedData(defendentPartyPersonList);

		witnessPersonModel = new ListDataModel();
		witnessPersonModel.setWrappedData(witnessPersonList);

		defendentsAttorneyModel = new ListDataModel();
		defendentsAttorneyModel.setWrappedData(defendentsAttorneyList);

		plantiffsAttorneyModel = new ListDataModel();
		plantiffsAttorneyModel.setWrappedData(plantiffsAttorneyList);
		
		List<Documents> pdfList = new ArrayList<Documents>();
		List<Documents>iDocs = new ArrayList<Documents>();
		List<Documents>eDocs = new ArrayList<Documents>();
		
		pdfList = this.getModelFacade().getPDFDocuments(caseUuid);
		boolean docOrder = false;
		boolean docSigned = false;
		
	/**
	 * 
	 * Code to check whether an Agent can Sign or not
	 */
		
		if (pdfList.size() != 0)
		{
			//custom Code to check whether the document can be signed or not for Agent for Morgan County
			

			
			for (Documents doc : pdfList) {
			

				docOrder = digitalSignerController.isDocumentOrderForAgent(doc);
				docSigned = digitalSignerController.isDocumentSignedByAgent(doc, p); 
				//unless an until the signDocument() method calls the visual Signature and update the database with documents Signature its gonna return false
				
				int i = 0;
				
				System.out.println("The document is the document Signed by the Agent :?" + docSigned);
					doc.setOrderedDoc(docOrder);
					doc.setSignedDoc(docSigned);
			
			}
			//caseStatus = "ReceivedBYAttorney" for statusCode=10;
			//caseStatus = "sentToAttorneyAddition" for statusCode=16;
			//caseStatus = "sentToAttorneyAddition" for statusCode=16;

			if (!((caseRecordStatus == 10) || (caseRecordStatus == 16)|| (caseRecordStatus == 11)) ) {
				this.updateDatabaseAfterAllSigned(pdfList, p);

			} else {
				this.setRenderSendToAttorneyButton(false);
				this.setRenderModifyButton(true);
			}
		}
		for(Documents document : pdfList) {
			int docStatusCode = document.getStatus().getCode();
			if(docStatusCode == Constants.DocumentStatus.IMPORTED) 
			{
				iDocs.add(document);
			} 
			else 
			{
				eDocs.add(document);
			}
		}
		
		this.setImportedDocumentsList(iDocs);
		this.setUploadedDocumentsList(eDocs);
		this.setDocumentList(pdfList);	

		importedDocumentsModel = new ListDataModel();
		uploadedDocumentsModel =  new ListDataModel();
		
		importedDocumentsModel.setWrappedData(this.getImportedDocumentsList());
		uploadedDocumentsModel.setWrappedData(this.getUploadedDocumentsList());

		// set court date
		this.setCourtDate(this.getModelFacade().findCourtDate(
				this.getCaseRecord().getUuid()));
		/*
		
		Integer caseTypeAction = null;
		String fromPage = (String) sessionMap.get("from");
		if(fromPage.equalsIgnoreCase("establishmentFilingPage")){
			caseTypeAction = (Integer) sessionMap.get("externalCaseCategoryCode");
		}else
		{
			caseTypeAction = c.getCaseRecordAction().getId();
		}
		
		
		if(caseTypeAction==3 && caseTypeAction!=null)
		*/
		if(c.getCaseRecordAction().getId()==3)
		{
			if( !defendentPartyPersonList.isEmpty() && !initiatingPartyOrganizationList.isEmpty())
			{
				String initiatingPartyOrgName = ((OrgParticipants) initiatingPartyOrganizationList
						.get(0)).getOrganizations().getName();
				Person defendent = ((PersonParticipants) defendentPartyPersonList
						.get(0)).getPerson();
				String defendentName = defendent.getFirstName() + " "
						+ defendent.getMiddleName() + " "
						+ defendent.getLastName();
				String etal = "";
				String PcaseCaption = String.format("DHS/%s vs %s",etal,defendentName);
				this.setCaseCaption(PcaseCaption);
			}
			else{
				//CASE IS INVALID
				validCase = false;
				this.setCaseCaption("DHS/INVALID CASE");
			}
			
		}
		// set case caption
		else
		{
		if ( !initiatingPartyOrganizationList.isEmpty() &&  !initiatingPartyPersonList.isEmpty() &&  !defendentPartyPersonList.isEmpty())
			 {
				String initiatingPartyOrgName = ((OrgParticipants) initiatingPartyOrganizationList
						.get(0)).getOrganizations().getName();
				Person defendent = ((PersonParticipants) defendentPartyPersonList
						.get(0)).getPerson();
				String defendentName = defendent.getFirstName() + " "
						+ defendent.getMiddleName() + " "
						+ defendent.getLastName();
				String etal = "";
				if(initiatingPartyPersonList.size() > 1)
				{
					etal = " et. al.";
				}
				String PcaseCaption = String.format("DHS/%s vs %s",								
						((PersonParticipants)initiatingPartyPersonList.get(0)).getPerson().getFirstName() + " " + 
						((PersonParticipants)initiatingPartyPersonList.get(0)).getPerson().getLastName() + etal,						
						defendentName);
				
				this.setCaseCaption(PcaseCaption);
			}else{
				//CASE IS INVALID
				validCase = false;
				this.setCaseCaption("DHS/INVALID CASE");
			}
		}
		
		
		//set OCSS case number
		List<CaseRecordIdExternalCaseRecordNumber> externalCaseIds = 
		    this.getModelFacade().findExternalCaseRecordNumbers(caseUuid);
		if (!externalCaseIds.isEmpty()) {
		    // TODO Need to have types to classify the external 
		    // identifiers
		    CaseRecordIdExternalCaseRecordNumber externalCaseId = externalCaseIds.get(0);
		    String externalCaseNumber = externalCaseId.getExternalCaseRecordNumber();
		    this.setOCSSCaseNumber(externalCaseNumber);
		}
				
		//set court case number(docketID)
		String docketID = c.getCaseTrackingId();
		this.setCourtCaseNumber(docketID);
		
		String fromPage = (String) sessionMap.get("from");
		String statusDescription = (String)this.getCaseRecord().getStatus().getDescription();
		int statusCode = this.getCaseRecord().getStatus().getCode();
		if (!fromPage.equalsIgnoreCase("trashcanPage")) {		
			if((statusDescription.equals("Unsent")) ||
					(statusDescription.equals("rejectedByAttorney")) ||
					//(statusDescription.equals("Rejected")) ||
					(statusDescription.equals("UnsentAddition"))) {
				this.setRenderModifyButton(true);
			} else {
				this.setRenderModifyButton(false);
			}
			if((statusDescription.equals("Unsent"))||
					(statusDescription.equals("rejectedByAttorney")) ||
					(statusDescription.equals("UnsentAddition"))) {
				this.setRenderSendToAttorneyButton(true);
			} else {
				this.setRenderSendToAttorneyButton(false);
			}
		}else {
			this.setRenderSendToAttorneyButton(false);
		}

		if ((fromPage.equalsIgnoreCase("searchPage") || (fromPage.equalsIgnoreCase("attFilingsTablesPage")) ||
				fromPage.equalsIgnoreCase("allFilingsTablesPage")) && 
				((statusCode == 2) || (statusCode == 1) || (statusCode == 20) || (statusCode == 6) || (statusCode == 3))) {
				// GAJETWOX-137: disposed cases need a new filing button also
			this.setRenderFileNewDocuments(true);
		}
		
		if(statusDescription.equals("UnsentAddition")) {
			
				//Render sendToClerkButton whenever it's "unsentaddition"
				this.setRenderSendToClerkButton(true);
			//TODO: Addition of "Return Incorrect Case" button on Case Details Page for 
			//cases of "UnsentAddition" status			
		} else {
			this.setRenderSendToClerkButton(false);
		}
		
		// sign by agent logic
		for (Documents doc : eDocs ) { //uploaded documents
			if(digitalSignerController.isDocumentSignedByAgent(doc, p))
			{
				this.setRenderSignButton(true);
			}else{
				this.setRenderSignButton(false);
			}
		}
		
		//if (courtUuid.equalsIgnoreCase("courtUuid4") && !statusDescription.equalsIgnoreCase("Unsent")) {
/*		if (courtUuid.equalsIgnoreCase("courtUuid4")) {
			this.setRenderSendToClerkButton(true);
		}*/
		
		if (courtUuid.equalsIgnoreCase("courtUuid4")) {
			for (Documents doc : eDocs ) { //uploaded documents
				int docCode = doc.getDocumentInstance().getCode();
				if (docCode == 738 || docCode == 739 || docCode == 733 || docCode == 744
						|| docCode == 745 || docCode == 746 || docCode == 747 || docCode == 748 || docCode == 749 || docCode == 750
						|| docCode == 702 || docCode == 705 || docCode == 728 || docCode == 751 || docCode == 752 || docCode == 753
						|| docCode == 730 || docCode == 734 || docCode == 741 || docCode == 742 || docCode == 743 || docCode == 726
						|| docCode == 754 || docCode == 755 || docCode == 756 || docCode == 762)
				this.setRenderSendToClerkButton(true);
			}
		}
		
		
		
		/*
		 * For Certain documents in Chatahm County when uploaded they can be directly send to Clerk
		 */
		if (courtUuid.equalsIgnoreCase("courtUuidChatham")) {
			for (Documents doc : eDocs ) { //uploaded documents
				int docCode = doc.getDocumentInstance().getCode();
				if (docCode == 25005 || docCode == 25006 || docCode == 25014 || docCode == 25015
						|| docCode == 25016 || docCode == 25017 || docCode == 25018 || docCode == 25019 || docCode == 25020 || docCode == 25021
						|| docCode == 25024 || docCode == 25025 || docCode == 25026 || docCode == 25027 || docCode == 25028)
				this.setRenderSendToClerkButton(true);
			}
		}
		
		
		
		/*
		 * For Certain documents in Clarke County when uploaded they can be directly send to Clerk
		 */
		if (courtUuid.equalsIgnoreCase("courtUuidClarke")) {
			for (Documents doc : eDocs ) { //uploaded documents
				int docCode = doc.getDocumentInstance().getCode();
				if (docCode == 26011 || docCode == 26012 || docCode == 26022 || docCode == 26023
						|| docCode == 26008 )
				this.setRenderSendToClerkButton(true);
			}
		}
		
		/*
		 * For Certain documents in Houston County when uploaded they can be directly send to Clerk
		 */
		if (courtUuid.equalsIgnoreCase("courtUuidHouston")) {
			for (Documents doc : eDocs ) { //uploaded documents
				int docCode = doc.getDocumentInstance().getCode();
				if (docCode == 270030 || docCode == 270031 || docCode == 270044 || docCode == 270060
						|| docCode == 280041 || docCode == 27003 || docCode == 27004 || docCode == 27005 || docCode == 27006 || docCode == 270020
						|| docCode == 27007 || docCode == 270021 || docCode == 270026 || docCode == 270029)
				this.setRenderSendToClerkButton(true);
			}
		}
		
		
		/*
		 * For Certain documents in Franklin County when uploaded they can be directly send to Clerk
		 */
		if (courtUuid.equalsIgnoreCase("courtUuidFranklin")) {
			for (Documents doc : eDocs ) { //uploaded documents
				int docCode = doc.getDocumentInstance().getCode();
				if (docCode == 86002 || docCode == 86007)
				this.setRenderSendToClerkButton(true);
			}
		}
		
		
		if(caseRecord.getStatus().getCode() == Constants.CaseRecordStatus.REJECTED)
		{
//			this.setRenderModifyButton(true);
			this.setRenderChooseAttorney(false);
			this.setRenderSendToAttorneyButton(true);
			this.setRenderRejectReason(true); 
			this.setRenderSendToClerkButton(true);
		}
		
		
		//if there is more than one attorney, render the choose attorney button
		this.setRenderChooseAttorney(this.getModelFacade().getLegalPreparers(p, org).size()>1);
		
		this.setRenderSendToClerkButton(true);
		
		if(!this.validCase)
		{
			this.setRenderModifyButton(false);
			this.setRenderSendToAttorneyButton(false);
			this.setRenderSendToClerkButton(false);
			this.setRenderFileNewDocuments(false);
			this.setRenderChooseAttorney(false);
		}
		

	}

	/**
	 * This method navigates user to the import filing page.
	 * @return String
	 */
	public String gotoImportFiling() {
		return "gotoImportFiling";
	}

	/**
	 * This method navigates user to the reject filing page.
	 * @return String
	 */
	public String gotoRejectFiling() {
		return "gotoRejectFiling";
	}

	/**
	 * This method navigates user to the previous page.
	 * @return
	 */
	public String back() {
		Map sessionMap = this.getFacesContext().getExternalContext()
				.getSessionMap();
		String fromPage = (String)sessionMap.get("from");
				
		if (fromPage.equalsIgnoreCase("allFilingsTablesPage")) {
			sessionMap.remove("caseUuid");
			return "allFilingsPage";
		}
		else if(fromPage.equalsIgnoreCase("trashcanPage")) {
			return "trashcanPage";
		}
		else if(fromPage.equalsIgnoreCase("establishmentFilingPage")) {
				return "establishmentFilingPage";
		} 
		else if (fromPage.equalsIgnoreCase("agentFilingsTablesPage")) 
			return "allFilingsPage";
		else if (fromPage.equalsIgnoreCase("searchPage")) {
			sessionMap.put("from", "attFilingsTablesPage");
			return "searchPage";
		}
		else return "";
	}
	
	/**
	 * Getter for property courtDate
	 * @return courtDate
	 */
	public Date getCourtDate() {
		return courtDate;
	}
	
	/**
	 * Setter for property courtDate
	 * @param courtDate
	 */
	public void setCourtDate(Date courtDate) {
		this.courtDate = courtDate;
	}
	
	/**
	 * @param initiatingPartyOrganizationDataModel
	 *            The initiatingPartyOrganizationDataModel to set.
	 */
	public void setInitiatingPartyOrganizationDataModel(
			DataModel initiatingPartyOrganizationDataModel) {
		this.initiatingPartyOrganizationDataModel = initiatingPartyOrganizationDataModel;
	}
	
	/**
	 * @return Returns the caseRecord.
	 */
	public CaseRecord getCaseRecord() {
		return caseRecord;
	}

	/**
	 * Setter for property caseRecord
	 * @param caseRecord
	 */
	public void setCaseRecord(CaseRecord caseRecord) {
		this.caseRecord = caseRecord;
	}

	/**
	 * Getter for property filerName
	 * @return filerName
	 */
	public String getFilerName() {
		return filerName;
	}

	/**
	 * Setter for property filerName
	 * @param filerName
	 */
	public void setFilerName(String filerName) {
		this.filerName = filerName;
	}

	/**
	 * Getter for property defendentPartyPersonModel
	 * @return defendentPartyPersonModel
	 */
	public DataModel getDefendentPartyPersonModel() {
		return defendentPartyPersonModel;
	}

	/**
	 * Setter for property defendentPartyPersonModel
	 * @param defendentPartyPersonModel
	 */
	public void setDefendentPartyPersonModel(DataModel defendentPartyPersonModel) {
		this.defendentPartyPersonModel = defendentPartyPersonModel;
	}

	/**
	 * Getter for property defendentsAttorneyModel
	 * @return defendentsAttorneyModel
	 */
	public DataModel getDefendentsAttorneyModel() {
		return defendentsAttorneyModel;
	}

	/**
	 * Setter for property defendentsAttorneyModel
	 * @param defendentsAttorneyModel
	 */
	public void setDefendentsAttorneyModel(DataModel defendentsAttorneyModel) {
		this.defendentsAttorneyModel = defendentsAttorneyModel;
	}

	/**
	 * Getter for property initiationgPartyPersonModel
	 * @return initiatingPartyPersonModel
	 */
	public DataModel getInitiatingPartyPersonModel() {
		return initiatingPartyPersonModel;
	}

	/**
	 * Setter for property initiatingPartyPersonmodel
	 * @param initiatingPartyPersonModel
	 */
	public void setInitiatingPartyPersonModel(
			DataModel initiatingPartyPersonModel) {
		this.initiatingPartyPersonModel = initiatingPartyPersonModel;
	}

	/**
	 * Getter for property initiatingPartyOrganizationDataModel
	 * @return initiatingPartyOrganizationDataModel
	 */
	public DataModel getInitiatingPartyOrganizationDataModel() {
		return initiatingPartyOrganizationDataModel;
	}

	/**
	 * Getter for property witnessPersonModel
	 * @return
	 */
	public DataModel getWitnessPersonModel() {
		return witnessPersonModel;
	}

	/**
	 * Setter for property witnessPersonModel
	 * @param witnessPersonModel
	 */
	public void setWitnessPersonModel(DataModel witnessPersonModel) {
		this.witnessPersonModel = witnessPersonModel;
	}

	/**
	 * Getter for property plantiffsAttorneyModel
	 * @return plantiffsAttorneyModel
	 */
	public DataModel getPlantiffsAttorneyModel() {
		return plantiffsAttorneyModel;
	}

	/**
	 * Setter for property plantiffsAttorneyModel
	 * @param plantiffsAttorneyModel
	 */
	public void setPlantiffsAttorneyModel(DataModel plantiffsAttorneyModel) {
		this.plantiffsAttorneyModel = plantiffsAttorneyModel;
	}

	/**
	 * Getter for property caseCaption
	 * @return caseCaption
	 */
	public String getCaseCaption() {
		return caseCaption;
	}

	/**
	 * Setter for property caseCaption
	 * @param caseCaption
	 */
	public void setCaseCaption(String caseCaption) {
		this.caseCaption = caseCaption;
	}

	/**
	 * @return the uploadedDocumentsList
	 */
	public List<Documents> getUploadedDocumentsList() {
		return uploadedDocumentsList;
	}

	/**
	 * @param uploadedDocumentsList the uploadedDocumentsList to set
	 */
	public void setUploadedDocumentsList(List<Documents> uploadedDocumentsList) {
		this.uploadedDocumentsList = uploadedDocumentsList;
	}

	/**
	 * @return the uploadedDocumentsModel
	 */
	public DataModel getUploadedDocumentsModel() {
		reload();
		return uploadedDocumentsModel;
	}

	private void reload() {
		Map sessionMap = this.getFacesContext().getExternalContext().getSessionMap();
		String caseUuid = (String) sessionMap.get("caseUuid");
		List<Documents> pdfList = new ArrayList<Documents>();
		List<Documents>iDocs = new ArrayList<Documents>();
		List<Documents>eDocs = new ArrayList<Documents>();
		
		pdfList = this.getModelFacade().getPDFDocuments(caseUuid);
		
		for(Documents document : pdfList) {
			int docStatusCode = document.getStatus().getCode();
			if(docStatusCode == Constants.DocumentStatus.IMPORTED) 
			{
				iDocs.add(document);
			} 
			else 
			{
				eDocs.add(document);
			}
		}
		
		this.setImportedDocumentsList(iDocs);
		this.setUploadedDocumentsList(eDocs);
		this.setDocumentList(pdfList);
		if(importedDocumentsModel==null)
			importedDocumentsModel = new ListDataModel();
		if(uploadedDocumentsModel==null)
			uploadedDocumentsModel =  new ListDataModel();
		
		importedDocumentsModel.setWrappedData(this.getImportedDocumentsList());
		uploadedDocumentsModel.setWrappedData(this.getUploadedDocumentsList());
		
	}

	/**
	 * @param uploadedDocumentsModel the uploadedDocumentsModel to set
	 */
	public void setUploadedDocumentsModel(DataModel uploadedDocumentsModel) {
		this.uploadedDocumentsModel = uploadedDocumentsModel;
	}

	/**
	 * @return the importedDocumentsList
	 */
	public List<Documents> getImportedDocumentsList() {
		return importedDocumentsList;
	}

	/**
	 * @param importedDocumentsList the importedDocumentsList to set
	 */
	public void setImportedDocumentsList(List<Documents> importedDocumentsList) {
		this.importedDocumentsList = importedDocumentsList;
	}

	/**
	 * @return the importedDocumentsModel
	 */
	public DataModel getImportedDocumentsModel() {
		reload();
		return importedDocumentsModel;
	}

	/**
	 * @param importedDocumentsModel the importedDocumentsModel to set
	 */
	public void setImportedDocumentsModel(DataModel importedDocumentsModel) {
		this.importedDocumentsModel = importedDocumentsModel;
	}

	/**
	 * @return the documentClicked_Uploaded
	 */
	public UIParameter getDocumentClicked_Uploaded() {
		return documentClicked_Uploaded;
	}

	/**
	 * @param documentClicked_Uploaded
	 *            the documentClicked_Uploaded to set
	 */
	public void setDocumentClicked_Uploaded(UIParameter documentClicked) {
		this.documentClicked_Uploaded = documentClicked;
	}
	
	/**
	 * @return the documentClicked_Imported
	 */
	public UIParameter getDocumentClicked_Imported() {
		return documentClicked_Imported;
	}

	/**
	 * @param documentClicked_Imported the documentClicked_Imported to set
	 */
	public void setDocumentClicked_Imported(UIParameter documentClicked_imported) {
		this.documentClicked_Imported = documentClicked_imported;
	}
	
	/**
	 * This method browse the clicked PDF file
	 * @return String
	 */
	public void viewFile() {
		
		Documents docUploaded = (Documents) this.getDocumentClicked_Uploaded().getValue();
		Documents docImported = (Documents) this.getDocumentClicked_Imported().getValue();
		Documents docToStream = docUploaded;
		
		//If the uploaded doc is null, try others
		if (docToStream == null) { 
			docToStream = docImported;
		} 

		if (docToStream != null) {
			FacesContext context = this.getFacesContext();
			HttpServletResponse resp = (HttpServletResponse) this.getFacesContext().getExternalContext().getResponse();
			String docTitle = docToStream.getTitle();
			byte[] docContent = docToStream.getContent();
			
			
			try {
				FileUtility.streamReportToBrowser(resp, docTitle, docContent);
			} catch (IOException e) {
				LOG.error("Error in CaseDetailPage.viewFile() method: " + e);
			}
			context.responseComplete();
		} else {
			LOG.debug("Error: Documents Contents Null, not able to be viewed.");
		}		
	}

	/**
	 * method to send uploaded files to attorney
	 * 
	 * Session map input:
	 * 	 caseUuid - the caseRecord
	 *   courtUuid - the courtUuid
	 * 
	 */
	public void sendToAttorney(String crUuid){
		LOG.debug("in sendToAttorney");
		
		Map sessionMap = this.getFacesContext().getExternalContext().getSessionMap();
		CaseRecord c = this.getModelFacade().findCaseRecordById(crUuid, courtUuid);
		int caseRecordStatusCode = c.getStatus().getCode();
		
		
		
		//Step 1: Change the Case Record Status to Recieved by Attorney
		
		if (caseRecordStatusCode == Constants.CaseRecordStatus.UNSENT ||
				caseRecordStatusCode == Constants.CaseRecordStatus.REJECTED_BY_ATTORNEY) {
			CaseRecordStatus crs = this.getModelFacade().findCaseRecordStatusByCode(10);
			c.setStatus(crs);
			//this.getModelFacade().updateCaseRecordStatus(uuid, crs, courtUuid);
		} else if(caseRecordStatusCode == Constants.CaseRecordStatus.UNSENT_ADDITION) {
			CaseRecordStatus crs = this.getModelFacade().findCaseRecordStatusByCode(Constants.CaseRecordStatus.SENT_TO_ATTORNEY_ADDITION);
			//this.getModelFacade().updateCaseRecordStatus(uuid, crs, courtUuid);
			c.setStatus(crs);
		} 
		
		
		//Step 2: Change the Document to be send to the Attorney

		for (Documents doc : c.getDocuments()){
		    	// Doc Status 6 = Uploaded
			if (doc.getStatus().getCode()==Constants.DocumentStatus.UPLOAD){  
				doc.setSentToAttorney(true);
			}
		}
		
		//Step 3:
		//Code added by Jogi To Delete the Attorneys Associated with The Case:
		// debug
		List<PersonParticipants> x= this.getModelFacade().getPersonParticipantByParticipantRelationshipCode(this.caseRecord, 4);
		LOG.debug("this.getModelFacade().getPersonParticipantByParticipantRelationshipCode(this.caseRecord, 4) returns a list of size "+
					x.size());
		if(this.getModelFacade().getPersonParticipantByParticipantRelationshipCode(this.caseRecord, 4).size() != 0)
		{
			List<PersonParticipants> AttorneyList= this.getModelFacade().getPersonParticipantByParticipantRelationshipCode(this.caseRecord, 4);
			for (PersonParticipants Attor : AttorneyList) {

				Person personParticipant = (Person) this.getModelFacade().findPersonbyID(Attor.getPerson().getUuid());
				List<CaseRecord> crList = this.getModelFacade().findCaseRecordsByPerson(personParticipant);
				LOG.info("List of related case Records for the PP "	+ crList.size());

				this.getModelFacade().deletePersonParticipants(Attor);
			}
		}
		
	
		
		
		
		String attorneyChosen = this.getChooseAttorneyValue();
		if(attorneyChosen == null)
			LOG.debug("this.getChooseAttorneyValue() returns null");
		else
			LOG.debug("this.getChooseAttorneyValue() returns "+attorneyChosen);
		
		
		if(attorneyChosen != null) {
			//The following if block is for testing multiple attorneys under kcreeder
			if (attorneyChosen.equalsIgnoreCase("fultonAttorneyUuid5")) {
				String assistantAttorneys[] = {"fultonAttorneyUuid5","fultonAttorneyUuid7","fultonAttorneyUuid8","fultonAttorneyUuid9"};
				for (String aa : assistantAttorneys) {
					Person aaPerson = this.getModelFacade().findPersonById(aa);
					PersonParticipants ppAttorney = new PersonParticipants();
					ppAttorney.setCaseRecord(this.caseRecord);
					ppAttorney.setPerson(aaPerson);
					ppAttorney.setUuid(UUID.randomUUID().toString());
					ppAttorney.setRelationship(this.getModelFacade().findParticipantRelationship(4));
					this.getModelFacade().getSession().save(ppAttorney);
					//HibernatePhaseListener.getSessionFactory().getCurrentSession().save(ppAttorney);
				}
			} 
			//End
			else {
				Person att = this.getModelFacade().findPersonById(attorneyChosen);
				PersonParticipants ppAttorney = new PersonParticipants();
				ppAttorney.setCaseRecord(this.caseRecord);
				ppAttorney.setPerson(att);
				ppAttorney.setUuid(UUID.randomUUID().toString());		
				ppAttorney.setRelationship(this.getModelFacade().findParticipantRelationship(4));
				this.getModelFacade().getSession().save(ppAttorney);
			}
		}else
		{
			// attorneyChosen is null
			courtUuid = (String) sessionMap.get("courtUuid");
			Person p = (Person) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("person");				
			Organizations o = ((PersonOrganizations)this.getModelFacade().findPersonOrganizationByCourtAndPerson(p,courtUuid)).getOrganization();
			List<LegalPreparer> packageTypeList = this.getModelFacade().getLegalPreparers(p, o);

			PersonParticipants ppAttorney = new PersonParticipants();
			ppAttorney.setCaseRecord(this.caseRecord);
			LOG.debug("ppAttorney.setPerson(packageTypeList.get(0).getAttorney().getPerson())");
			ppAttorney.setPerson(packageTypeList.get(0).getAttorney().getPerson());
			LOG.debug("ppAttorney.setUuid(UUID.randomUUID().toString())");
			ppAttorney.setUuid(UUID.randomUUID().toString());		
			ppAttorney.setRelationship(this.getModelFacade().findParticipantRelationship(4));
			this.getModelFacade().getSession().save(ppAttorney);

		
		}
		
					
		//remove the caseUuid from session
		sessionMap.remove("caseUuid");
		sessionMap.remove("caseRecord");
		sessionMap.remove("agentCaseDetailsPage");	
		
		//track case record history		
	    CaseRecordHistory crh = new CaseRecordHistory();
		crh.setCaseRecord(caseRecord);
		crh.setEventDateTime(DateUtil.getCurrentDate());
		crh.setPerson( (Person) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("person"));		
		
		// Case Record Event - 9 = Filing Sent to Attorney
		crh.setEventType(this.getModelFacade().findCaseRecordEventType(Constants.CaseRecordEventType.FILING_RECEIVED_BY_ATTORNEY));
		crh.setComments(getComments());
		this.getModelFacade().insertCaseRecordHistory(crh);
				
	}
	
	/**
	 * Method to set court case number for Fulton county's contempt case
	 */
	public void updateCourtCaseNumber(){
		Map sessionMap = this.getFacesContext().getExternalContext().getSessionMap();
		String crUuid = (String) sessionMap.get("caseUuid");
		CaseRecord c = this.getModelFacade().findCaseRecordById(crUuid,courtUuid);
			this.getModelFacade().updateCaseRecordCourtTrackingID(crUuid, this.courtCaseNumber, courtUuid);
	}
	
	
	public String getSendToCourtText()
	{
		return this.sendToCourtAction.getText(this.courtUuid);
		
	}
	
	
	
	/**
	 * Method to send existing case direct to Court Clerk
	 */
	public void sendToClerk(String crUuid){
		
		Map sessionMap = this.getFacesContext().getExternalContext().getSessionMap();
		Person person = (Person) this.getFacesContext()
		.getExternalContext().getSessionMap().get("person");		
		CaseRecord c = this.getModelFacade().findCaseRecordById(crUuid, courtUuid);
		
		//SendToCourtAction sendToCourtAction = new SendToCourtAction();
		
		
		if(c.getStatus().getCode() == Constants.CaseRecordStatus.UNSENT_ADDITION
			|| c.getStatus().getCode() == Constants.CaseRecordStatus.UNSENT
			|| c.getStatus().getCode() == Constants.CaseRecordStatus.REJECTED
			|| c.getStatus().getCode() == Constants.CaseRecordStatus.READY_TO_SEND_TO_COURT			
				) {
			
			int newStatusCode = 0;
			int eventType = 0;
			if(sendToCourtAction.isClerkModuleDisabled(courtUuid))
			{		
				
				
				for(Documents doc : caseRecord.getDocuments())
				{												
					if(doc.getStatus().getCode()!=2)
					{										
						if(!doc.getContentAsFileHandle().exists()){
							caseRecord.setStatus(this.getModelFacade().findCaseRecordStatusByCode(Constants.CaseRecordStatus.FAILED_TO_IMPORT));							
						}
					}
				}
				
				if(GenericImportAction.isVendor(this.getModelFacade(),"XMLLEGAL",courtUuid))
				{
					caseRecord.setFilingId(UUID.randomUUID().toString().replaceAll("-",""));
				}else{
					caseRecord.setFilingId(caseRecord.getUuid());
				}
				
				this.getModelFacade().updateCaseRecord(caseRecord, courtUuid);							
				
				eventType = Constants.CaseRecordEventType.FILING_QUEUED_FOR_IMPORT_BY_AGENT;
				newStatusCode = Constants.CaseRecordStatus.QUEUED_FOR_IMPORT;
				
				/* Update the document status also */
				for(Documents d : c.getDocuments())
				{
					/* Queue documents which have never been imported before */
					if(d.getStatus().getCode() != 
							Constants.DocumentStatus.IMPORTED)
					{								
						
						DocumentStatus queuedForImport = this.getModelFacade().findDocumentStatus(
								Constants.DocumentStatus.QUEUED_FOR_IMPORT);
						this.getModelFacade().updateDocumentStatus(d.getUuid(),queuedForImport);
					}
				}				
			}else{
				eventType = Constants.CaseRecordEventType.FILING_RECEIVED_BY_CLERK;
				newStatusCode = Constants.CaseRecordStatus.RECEIVED;
			}
			
			CaseRecordStatus crs = this.getModelFacade().findCaseRecordStatusByCode(newStatusCode);
			this.getModelFacade().updateCaseRecordStatus(crUuid, crs, courtUuid);
			this.getModelFacade().addCaseRecordHistory(crUuid, eventType, person, courtUuid,getComments());
			
			
			
			
		}
		//remove the caseUuid from session
		sessionMap.remove("caseUuid");
		sessionMap.remove("caseRecord");
		sessionMap.remove("agentCaseDetailsPage");		
	}
	
	/**
	 * Method to file new documents to existing case
	 */
	public String fileNewDocuments() {
		
		Map sessionMap = this.getFacesContext().getExternalContext().getSessionMap();
		sessionMap.put("caseRecord", this.getCaseRecord());
		Person person = (Person) this.getFacesContext().getExternalContext().getSessionMap().get("person");
		String crUuid = (String) sessionMap.get("caseUuid");
		CaseRecordStatus crs = this.getModelFacade().findCaseRecordStatusByCode(15);
		this.getModelFacade().updateCaseRecordStatus(crUuid, crs, courtUuid);
		this.getModelFacade().addCaseRecordHistory(crUuid, 13, person, courtUuid,getComments());  //Filing Readied For Addition
		sessionMap.put("externalCaseCategoryCode",this.getCaseRecord().getCaseRecordAction().getId());
		String toString = "fileNewDocuments";
		return toString;
	}

	public String submitCourtDate() {
		

		// this.getModelFacade().updateCourtDate(this.getCaseRecord().getUuid(),this.getProposedCourtDate());
		//Start the transaction
		//HibernatePhaseListener.getSessionFactory().getCurrentSession()
		//	.getTransaction().begin();
		
		
		Person personLoggingIn = (Person) this.getFacesContext()
			.getExternalContext().getSessionMap().get("person");
		String updatePersonUuid = personLoggingIn.getUuid();
		
		
		
		this.getModelFacade().updateCourtDate(this.getCaseRecord().getUuid(),
				this.getProposedCourtDate(), updatePersonUuid);
		//Frank added the following block to track the caseRecord
		
		
		
		this.setCourtDate(proposedCourtDate);
		CaseRecordHistory crh = new CaseRecordHistory();
		crh.setCaseRecord(caseRecord);
		// Set event to "Attorney Set Court Date" (21)
		crh.setEventType(this.getModelFacade().findCaseRecordEventType(12));
		crh.setEventDateTime(DateUtil.getCurrentDate());
		crh.setPerson(personLoggingIn);
		this.getModelFacade().insertCaseRecordHistory(crh);
		
	//End
		
		// this.getModelFacade().updateCourtHearingNegotiationStausToRejected(this.getCourtHearingNegotiations());
		
		//Added by Frank to put court date onto Rule NISI
			for (Documents doc : documentList) {
				int docTypeCode = doc.getDocumentInstance().getDocumentType()
					.getCode();
				int docStatusCode = doc.getStatus().getCode();
				byte[] originalContent = doc.getContent();
				if ((docTypeCode == 27) && (docStatusCode == 1 || 
						docStatusCode == 4 || docStatusCode == 6)  ) {
					
					PDFStamper pdfStamper = new PDFStamper();
					String targetForAttorneySignedDate = "+";
					byte[] newContent = pdfStamper.addDate(doc, this.getProposedCourtDate(),
							targetForAttorneySignedDate);
					//this.getModelFacade().makePersistenet(doc);
					if (newContent != null) {
					    doc.setContent(null,newContent);
					} else {
					    doc.setContent(null,originalContent);
					    LOG.debug("Court Date target not " +
					    		"found in document. " +
					    		"Contents Unchanged.");
					}
				}
			}
		//End	
			
		// commit the transaction
		///	HibernatePhaseListener.getSessionFactory().getCurrentSession()
		//	.getTransaction().commit();

		return "stay";
	}

	public void validateDate(FacesContext context, UIComponent component,
			Object value) throws ValidatorException, Exception {
		java.util.Date newValue = (java.util.Date) value;

		/*
		 * There is a bug in jsf page to pass over a date value, the passed
		 * value is always 1 day behind . The day field of the Calendar object
		 * starts with 1 but the month field starts with 0. This confusion might
		 * be the cause of the bug.
		 */
		if (!isValidDate(newValue)) {
			message.setSeverity(FacesMessage.SEVERITY_ERROR);
			throw new ValidatorException(message);
		}
		Calendar c = new GregorianCalendar();
		c.setTime(newValue);

		int date = c.get(Calendar.DATE);
		c.set(Calendar.DATE, date + 1);
		newValue = c.getTime();

		
	}

	/**
	 * Utiltiy method to validate date.
	 * 
	 * true if the new entered date is either equal to current date or a future
	 * date.
	 * 
	 * @param value
	 *            Date
	 * @return boolean
	 */
	protected boolean isValidDate(java.util.Date value) throws Exception {
		boolean validField = false;
		if ((value.compareTo(DateUtil.getCurrentDate()) <= 0) ) {
			validField = false;
			message = Messages.getMessage(
					"us.gaaoc.framework.webapp.util.errorMessage",
					"incorrectDate", null);
			message.setDetail(message.getDetail());
			message.setSeverity(FacesMessage.SEVERITY_ERROR);
		} else {
			Calendar cal = new GregorianCalendar();
			cal.setTime(value);
			int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
			if(dayOfWeek == 1 || dayOfWeek == 7) {
				validField = false;
				message = Messages.getMessage(
						"us.gaaoc.framework.webapp.util.errorMessage",
						"incorrectDate", null);
				message.setDetail(message.getDetail());
				message.setSeverity(FacesMessage.SEVERITY_ERROR);
			}else {
				validField = true;
			}
		}
		return validField;
	}
	
	
	/**
	 * Getter for property documentList
	 * @return documentList
	 */
	public List<Documents> getDocumentList() {
		return documentList;
	}

	/**
	 * Setter for property documentList
	 * @param documentList
	 */
	public void setDocumentList(List<Documents> documentList) {
		this.documentList = documentList;
	}

	/**
	 * @return the renderModifyButton
	 */
	public boolean isRenderModifyButton() {
		return renderModifyButton;
	}

	/**
	 * @param renderModifyButton the renderModifyButton to set
	 */
	public void setRenderModifyButton(boolean renderModifyButton) {
		this.renderModifyButton = renderModifyButton;
	}

	/**
	 * @return the renderSendToAttorneyButton
	 */
	public boolean isRenderSendToAttorneyButton() {
		return renderSendToAttorneyButton;
	}

	/**
	 * @param renderSendToAttorneyButton the renderSendToAttorneyButton to set
	 */
	public void setRenderSendToAttorneyButton(boolean renderSendToAttorneyButton) {
		this.renderSendToAttorneyButton = renderSendToAttorneyButton;
	}

	
	/**
	 * This method navigates user to the creating new filing page where
	 * Client can modify the existed filing.
	 * @return String
	 */
	public String modifyFiling() {
		String navigationString = "";
		Map sessionMap = this.getFacesContext().getExternalContext().getSessionMap();
		sessionMap.put("caseRecord", this.getCaseRecord());
		sessionMap.put("externalCaseCategoryCode",this.getCaseRecord().getCaseRecordAction().getId());
		navigationString = "modify";
		return navigationString;
	}

	/**
	 * @return the renderSendToClerkButton
	 */
	public boolean isRenderSendToClerkButton() {
		return renderSendToClerkButton;
	}

	/**
	 * @param renderSendToClerkButton the renderSendToClerkButton to set
	 */
	public void setRenderSendToClerkButton(boolean renderSendToClerkButton) {
		this.renderSendToClerkButton = renderSendToClerkButton;
	}

	/**
	 * @return the jurisdiction
	 */
	public String getJurisdiction() {
		return jurisdiction;
	}

	/**
	 * @param jurisdiction the jurisdiction to set
	 */
	public void setJurisdiction(String jurisdiction) {
		this.jurisdiction = jurisdiction;
	}

	public boolean isRenderRejectReason() {
		return renderRejectReason;
	}

	public void setRenderRejectReason(boolean renderRejectReason) {
		this.renderRejectReason = renderRejectReason;
	}

	public String getOCSSCaseNumber() {
		return OCSSCaseNumber;
	}

	public void setOCSSCaseNumber(String caseNumber) {
		OCSSCaseNumber = caseNumber;
	}

	public String getCourtCaseNumber() {
		return courtCaseNumber;
	}

	public void setCourtCaseNumber(String courtCaseNumber) {
		this.courtCaseNumber = courtCaseNumber;
	}

	public boolean isRenderFileNewDocuments() {
		return renderFileNewDocuments;
	}

	public void setRenderFileNewDocuments(boolean renderFileNewDocuments) {
		this.renderFileNewDocuments = renderFileNewDocuments;
	}

	public void setRenderChooseAttorney(boolean isRenderChooseAttorney) {
		this.isRenderChooseAttorney = isRenderChooseAttorney;
	}

	public boolean isRenderChooseAttorney() {
		return isRenderChooseAttorney;
	}

	public void setChooseAttorneyValue(String chooseAttorneyValue) {
		this.chooseAttorneyValue = chooseAttorneyValue;
	}

	public String getChooseAttorneyValue() {
		return chooseAttorneyValue;
	}

	public void setChooseAttorneyBinding(UISelectOne chooseAttorneyBinding) {
		this.chooseAttorneyBinding = chooseAttorneyBinding;
	}

	public UISelectOne getChooseAttorneyBinding() {
		return chooseAttorneyBinding;
	}
	public boolean isRenderUpdateCourtCaseNumber() {
		return renderUpdateCourtCaseNumber;
	}

	public void setRenderUpdateCourtCaseNumber(boolean renderUpdateCourtCaseNumber) {
		this.renderUpdateCourtCaseNumber = renderUpdateCourtCaseNumber;
	}

	/**
	 * @return the proposedCourtDate
	 */
	public Date getProposedCourtDate() {
		return proposedCourtDate;
	}

	/**
	 * @param proposedCourtDate
	 *            the proposedCourtDate to set
	 */
	public void setProposedCourtDate(Date proposedCourtDate) {
		this.proposedCourtDate = proposedCourtDate;
	}
	
	public boolean isRenderCourtDate() {
		return renderCourtDate;
	}

	public void setRenderCourtDate(boolean renderCourtDate) {
		this.renderCourtDate = renderCourtDate;
	}


	
	/**
	 * Code for Agent to Sign Starts here
	 * 
	 */
	
	//Getters and Setters
	
	public DigitalSignerController getDigitalSignerController() {
		return digitalSignerController;
	}

	public void setDigitalSignerController(
			DigitalSignerController digitalSignerController) {
		this.digitalSignerController = digitalSignerController;
	}

	public PDFStamperController getPdfStamperController() {
		return pdfStamperController;
	}

	public void setPdfStamperController(PDFStamperController pdfStamperController) {
		this.pdfStamperController = pdfStamperController;
	}
	

	public String getCaseRecordUuid() {
		return caseRecordUuid;
	}

	public void setCaseRecordUuid(String caseRecordUuid) {
		this.caseRecordUuid = caseRecordUuid;
	}

	public UIParameter getSignatureBinding() {
		return signatureBinding;
	}

	public void setSignatureBinding(UIParameter signatureBinding) {
		this.signatureBinding = signatureBinding;
	}
	
	
	
	//Methods to make the Agent Signature work starts here
	
	


	public boolean isRenderSignedText() {
		return renderSignedText;
	}

	public void setRenderSignedText(boolean renderSignedText) {
		this.renderSignedText = renderSignedText;
	}

	public boolean isRenderSetCourtDate() {
		return renderSetCourtDate;
	}

	public void setRenderSetCourtDate(boolean renderSetCourtDate) {
		this.renderSetCourtDate = renderSetCourtDate;
	}

	public boolean isRenderSignButton() {
		return renderSignButton;
	}

	public void setRenderSignButton(boolean renderSignButton) {
		this.renderSignButton = renderSignButton;
	}

	public String getCourtUuid() {
		return courtUuid;
	}

	public void setCourtUuid(String courtUuid) {
		this.courtUuid = courtUuid;
	}
	
	

	public Documents getSignedDoc() {
		return signedDoc;
	}

	public void setSignedDoc(Documents signedDoc) {
		this.signedDoc = signedDoc;
	}

	private boolean isAllDocumentsSignedByAgent(List<Documents> docs, Person person) {
		boolean documentsSigned = false;
		boolean ordered = false;
		List<Documents> orderedDocs = new ArrayList<Documents>();
		for (Documents d : docs) {
			ordered = digitalSignerController.isDocumentOrderForAgent(d);			
			if (ordered) {
				orderedDocs.add(d);
			}
		}
		List<Signatures> docSignatures = new ArrayList<Signatures>();
		if(! orderedDocs.isEmpty()) {
			for (Documents oDoc : orderedDocs) {
				docSignatures = oDoc.getSignatures();
				documentsSigned = false;
				for (Signatures s : docSignatures) {
					Person personSigned = s.getSignedByPerson();
					System.out.println("Signed Person Uuid "
							+ personSigned.getUuid());
					System.out.println("Parameter passes Person Uuid "
							+ person.getUuid());
					if (personSigned.getUuid().equals(person.getUuid())) {
						documentsSigned = true;
						break;
					}
					//break;
				}
				if (!documentsSigned) 
					break;		
			}
		}else {
			documentsSigned = true;
		}
		return documentsSigned;
	}

	/**
	 * 
	 * @param docs
	 * @param person
	 * 
	 * This method when called by the loadData() Method will update the database with Case Status=7 and also the 
	 * CaseRecordHistory table will be updated with eventypecode 41
	 */
	private void updateDatabaseAfterAllSigned(List<Documents> docs,	Person person)
	{
		CaseRecord caseRecord = this.getCaseRecord();
		//System.out.println("The CaseRecord UUID Passed to the updateDatabaseAfterAllSigned() method is: "+ caseRecord.getUuid().toString());
		/* Codes:
		 * 
		 * CaseRecordStatus 3: Rejected(By Clerk)
		 * CaseRecordStatus 10: SentToAttorney
		 * CaseRecordStatus 16: SentToAttorneyAddition
		 * CaseRecordStatus 11: ReadyToSendToCourt
		 */
		CaseRecordStatus caseStatus = caseRecord.getStatus();
		boolean allDocsSigned = this.isAllDocumentsSignedByAgent(docs, person);

		if (allDocsSigned)
		{
			System.out.println("The CaseRecord UUID for this is "+ caseRecord.getUuid().toString());

		 	this.getModelFacade().updateCaseRecordStatus(caseRecord.getUuid().toString(),caseStatus, courtUuid);

		 	/**
		 	 * The Case Record History is not recorded when the Agent  has signed the Document
		    CaseRecordHistory crh = new CaseRecordHistory();
			crh.setCaseRecord(caseRecord);
			crh.setEventDateTime(DateUtil.getCurrentDate());
			crh.setPerson(person);
			//HibernatePhaseListener.getSessionFactory().getCurrentSession().getTransaction().begin();
			crh.setEventType(this.getModelFacade().findCaseRecordEventType(41));
			this.getModelFacade().insertCaseRecordHistory(crh);
			//HibernatePhaseListener.getSessionFactory().getCurrentSession().getTransaction().commit();
		*/
			
			this.setRenderSendToAttorneyButton(true);
			this.setRenderModifyButton(true);
		} 
		else
		{
			this.setRenderSendToAttorneyButton(false);
			this.setRenderModifyButton(true);
		}
	}
	
	
	//Added by Frank
	private boolean isAllDocumentsImported(List<Documents> docs) {
		boolean allDocumentImported = false;
		for (Documents doc : docs) {
			if (doc.getStatus().getCode() != 2) {
				allDocumentImported = false;
				break;
			} else {
				allDocumentImported = true;
			}
		}
		return allDocumentImported;
	}
	
	@Transactional
	public String deleteDocument() {
		Documents doc = (Documents) this.getSignatureBinding().getValue();
		this.getModelFacade().enableDocDeleteFlag(doc);
		this.getModelFacade().getSession().delete(doc);
		return "stay";		
	}
	
	@Transactional
	public void deleteDocument(Documents doc ) {		
		this.getModelFacade().enableDocDeleteFlag(doc);
		this.getModelFacade().getSession().delete(doc);
			
	}
	
	
	//TODO: move this method into DocumentSigner bean
	// Frank added the following methods on 3.28.07
	/**
	 * This method is get called when user press the sign button to sign PDF or
	 * XML document
	 * 
	 * @return String
	 * @throws Exception
	 */
	public String signDocument() throws Exception {

			
				
		//HibernatePhaseListener.getSessionFactory().getCurrentSession().getTransaction().begin();
		LOG.debug("(Documents) this.getSignatureBinding().getValue()");
		Documents doc = (Documents) this.getSignatureBinding().getValue();	
		if (doc == null)
			LOG.debug("(Documents) this.getSignatureBinding().getValue() returns null");
		//save original document content in case signature failed
		byte[] originalDocContent = doc.getContent();
		
		byte[] sigInByte = null;
		
		Map sessionMap = this.getFacesContext().getExternalContext().getSessionMap();
		// Retrieve Person from the session
		Person personSigner = (Person)sessionMap.get("person");
		String agentRoleUuid = "uuid5"; // The Attorney Role UUID
		
		CaseRecord cr = this.getCaseRecord();
		//int documentCategory = doc.getDocumentInstance().getDocumentType().getDocumentCategory().getCode();
		
		
		// Retrieve the certificate password
		LdapDirectoryPerson ldPerson = this.getModelFacade().findLdapDirectoryByPerson(personSigner);
				
		// Add visual signature first	
		//HibernatePhaseListener.getSessionFactory().getCurrentSession().getTransaction().commit();
		//HibernatePhaseListener.getSessionFactory().getCurrentSession().beginTransaction();
		//loadData();
		//pdfStamperController.addVisualSignatureOnDocument(doc,personSigner,ldPerson,agentRoleUuid);
		pdfStamperController.addVisualSignatureOnDocument(doc,personSigner,agentRoleUuid);
		//HibernatePhaseListener.getSessionFactory().getCurrentSession().getTransaction().commit();
		//HibernatePhaseListener.getSessionFactory().getCurrentSession().beginTransaction();
	//loadData();
		// If visual Signature is successfully put on the document then digitally sign
		if(pdfStamperController.isSignedDoc() == true) {
			//sigInByte = digitalSignerController.signDocument(doc, personSigner,agentRoleUuid, ldPerson);
			sigInByte = digitalSignerController.signDocument(doc, personSigner,agentRoleUuid);
			// update the signed field in the documents object
			DocumentStatus documentStatus  = new DocumentStatus();
			if(digitalSignerController.isSignedDoc() == true) {
				int statusCode = 18;			//signedByAgent
				documentStatus = this.getModelFacade().findDocumentStatus(statusCode);
				digitalSignerController.updateDatabaseAfterSigned(doc,
						documentStatus, personSigner, sigInByte);
			}
			// update the signed field in the documents object
			doc.setSignedDoc(digitalSignerController.isSignedDoc());
			// for rendering purpose in the xhtml page set the field ordered as false
			doc.setOrderedDoc(digitalSignerController.isOrderedDoc());		
		}
		//Check the status of the doc and if it is 
		//failedAttorneySignature for the clerk then set the corresponding booleans
		//that cause the message to appear on the page indicating the documents
		//with the problem and also for the sign command to reappear
	
		//HibernatePhaseListener.getSessionFactory().getCurrentSession().getTransaction().begin();
//	b7006e6c-695c-11dd-945f-00301b45ff56
		if (doc.getContent() == null){	
			doc.setContent(null,originalDocContent);
			CaseRecordHistory crh = new CaseRecordHistory();
			crh.setCaseRecord(caseRecord);
			crh.setEventDateTime(DateUtil.getCurrentDate());
			crh.setPerson(personSigner);
			//HibernatePhaseListener.getSessionFactory().getCurrentSession().getTransaction().begin();
			/**
			 * EventTypeCode = 42 Filing Not Accepted By OCSS Office due to Agent Signature
			 */
			crh.setEventType(this.getModelFacade().findCaseRecordEventType(42));
			this.getModelFacade().insertCaseRecordHistory(crh);
			//HibernatePhaseListener.getSessionFactory().getCurrentSession().getTransaction().commit();
		}else if(doc.getStatus().getCode() == 17){
			//Clerk signature failure not necessarily from no contents
			//set the document content with the original content
			doc.setContent(null,originalDocContent);
			CaseRecordHistory crh = new CaseRecordHistory();
			crh.setCaseRecord(caseRecord);
			crh.setEventDateTime(DateUtil.getCurrentDate());
			crh.setPerson(personSigner);
			//HibernatePhaseListener.getSessionFactory().getCurrentSession().getTransaction().begin();
			/**
			 * EventTypeCode = 43 Missing Agent Signature
			 */
			crh.setEventType(this.getModelFacade().findCaseRecordEventType(43));
			this.getModelFacade().insertCaseRecordHistory(crh);
			
		}	
		
		boolean docOrder;
		boolean docSigned;
		for (Documents docx : this.caseRecord.getDocuments()) {
			docOrder = digitalSignerController.isDocumentOrderForAgent(docx);
			docSigned = digitalSignerController.isDocumentSignedByAgent(docx, personSigner);
			if (docOrder) {
				if (!docSigned && !docx.getUuid().equalsIgnoreCase(doc.getUuid())) {
				}
			}
		}
		//loadData();


		//HibernatePhaseListener.getSessionFactory().getCurrentSession().getTransaction().commit();
		return "stay";		
	}
	/**
	 * This method navigates user to display the details of Signature on the
	 * next page
	 * 
	 * @return
	 * @throws Exception
	 * 
	 * Writer: Michael A.
	 */
	public String viewSignatureDetails() throws Exception {
		return "viewSignatureDetails";
	}
	
	public void onCaseUuidChange(String caseUuid){
		Map sessionMap = FacesContext.getCurrentInstance().getExternalContext().getSessionMap();	 	
	 	sessionMap.put("caseUuid", caseUuid);
	 	sessionMap.put("from", "trashcanPage");	 
	 	this.loadData();
	 }
	
	
}